package com.yc.vote.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.databind.ObjectMapper;

public class BaseController extends HttpServlet{
	private static final long serialVersionUID = -2184950581665513953L;
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req,resp);
	}
	
	protected void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
		//要根据请求转化到不同的控制器中
		String url = request.getRequestURI(); // 获取请求地址 /vote/user/login
		String path = url.substring(url.lastIndexOf("/") + 1); // login
		
		Method[] methods = this.getClass().getDeclaredMethods(); // 获取这个类中的所有的方法
		
		//循环所有的方法，看是否有我们需要的方法
		for(Method method : methods) {
			
			if(path.equals(method.getName())) { // 说明就是要调这个方法执行
				System.out.println(method.getName());
				try {
					method.invoke(this, request, response);
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				} catch (IllegalArgumentException e) {
					e.printStackTrace();
				} catch (InvocationTargetException e) {
					e.printStackTrace();
				}
				return;
			}
		}
		this.error(request, response);
	}

	private void error(HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.setContentType("text/html; charset=utf-8");
		PrintWriter out = response.getWriter();
		//http://127.0.0.1:8080/vote
		String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getServletPath();
		out.print("<script>alert('该请求不支持...');location.href='" + basePath + "index.html';</script>");
		out.flush();
		out.close();
	} 
	
	protected void send(HttpServletResponse response, int code, Object data) throws IOException {
		response.setContentType("text/plain; charset=utf-8");
		PrintWriter out = response.getWriter();
		ObjectMapper mapper = new ObjectMapper();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("code", code);
		map.put("data", data);
		out.print(mapper.writeValueAsString(map));
		out.flush();
		out.close();
	}
	
	protected void send(HttpServletResponse response, Object data) throws IOException {
		response.setContentType("text/plain; charset=utf-8");
		PrintWriter out = response.getWriter();
		ObjectMapper mapper = new ObjectMapper();
		out.print(mapper.writeValueAsString(data));
		out.flush();
		out.close();
	}
}
